package com.lian.hope.utils;

import com.lian.hope.properties.AlisSmsProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.CompletableFuture;

@Component
@RequiredArgsConstructor
public class SmsSenderUtil {

    private final AlisSmsProperties alisSmsProperties;

    /**
     * 发送验证码
     *
     * @param phoneNumber
     * @return
     */
    public String sendSms(String phoneNumber) {
        StaticCredentialProvider provider = createCredentialProvider();
        AsyncClient client = createAsyncClient(provider);

        String code = getCode();
        SendSmsRequest sendSmsRequest = createSendSmsRequest(code, phoneNumber);
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        System.out.println("response：" + response);

        client.close();

        return code;
    }

    /**
     * 创建静态凭证提供其
     *
     * @return
     */
    private StaticCredentialProvider createCredentialProvider() {
        return StaticCredentialProvider.create(Credential.builder().accessKeyId(alisSmsProperties.getAccessKeyId())
            .accessKeySecret(alisSmsProperties.getAccessKeySecret()).build());
    }

    /**
     * 创建异步客户端
     *
     * @param provider
     * @return
     */
    private AsyncClient createAsyncClient(StaticCredentialProvider provider) {
        return AsyncClient.builder().region(alisSmsProperties.getRegion()).credentialsProvider(provider)
            .overrideConfiguration(
                ClientOverrideConfiguration.create().setEndpointOverride(alisSmsProperties.getEndpointOverride()))
            .build();
    }

    /**
     * 生成随机六位数验证码
     *
     * @return
     */
    private String getCode() {
        Random random = new Random();
        int code = random.nextInt(900000) + 100000;
        return String.valueOf(code);
    }

    private SendSmsRequest createSendSmsRequest(String code, String phoneNumber) {
        return SendSmsRequest.builder().signName(alisSmsProperties.getSignName()).templateCode(
                alisSmsProperties.getTemplateCode()).phoneNumbers(phoneNumber).templateParam("{\"code\":\"" + code +
                                                                                             "\"}")
            .build();
    }

}
